package com.zj.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.zj.config.AliyunOssConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 自己的名字
 * @version 1.0.0
 * @ClassName UploadService
 * @Description aliyun oss imp
 * @createTime 2024年12月17日 20:05
 */
@Service
public class UploadService {
    @Autowired
    private AliyunOssConfig aliyunOssConfig;

    public String upload(MultipartFile file){
        String bucketname = aliyunOssConfig.getBucketname();
        String accessKeyId = aliyunOssConfig.getAccessKeyId();
        String endpoint = aliyunOssConfig.getEndpoint();
        String accessKeySecret = aliyunOssConfig.getAccessKeySecret();
        //get oss client
        OSS oss = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        String filename = file.getOriginalFilename();
        String now = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        String extendsion = filename.substring(filename.lastIndexOf("."));
        //create folder
        String newFileName = "user/" + now + "/" + filename + "/" + extendsion;
        try {
            PutObjectResult result = oss.putObject(bucketname, newFileName, file.getInputStream());
            if (result != null){
                return "https://"+bucketname+"."+endpoint+"/"+newFileName;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            oss.shutdown();
        }
        return "";

    }
}
